// pages/user/putForwardPrice/putForwardPrice.js
var app = getApp();
var isRepeat = false;
var withdrawConfig = [], workers_info = [];//兑换配置,经销商账户信息;

let isSend = false;
let timer = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prohibit: false, //选择银行卡弹窗
    isChoose: true, //未选择兑换账户
    banks: [], //银行卡列表
    bank_id: 0,
    total: 0,
    money: 0,
    poundage: 0,
    allMoney: '',
    actualMoney:'',//实际到账
    msg:'',
    isForward: false,//是否能兑换

    role: 6,// 角色,4:用户,6:经销商,默认6

    codeShow: false, //验证弹窗
    accountType: '', //账户类型 1 银行卡，2 微信零钱
    is_phone: false, //是否已授权手机号码
    auth_phone: '', //授权的用户信息
    inputIndex: 0, //聚焦索引
    inputValue: '', //输入验证码value
    inputArr: [], //验证码分割后的数组
    codeShow: false, //验证弹窗
    sms_txt: '',//短信提示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      role: options.role,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.withdrawConfig();
    this.withdrawDepositInfo();
    isRepeat = false;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  // 计算手续费
  checkMoney() {
    var that = this;
    //账户余额
    var account_balance = parseFloat(workers_info.available_money);
    //输入金额
    var val = that.data.money;

    var percentage = that.data.accountType == 1 ? parseFloat(withdrawConfig.value.percentage) : parseFloat(withdrawConfig.value.wx_percentage);
    var min = parseFloat(withdrawConfig.value.min);
    var max = parseFloat(withdrawConfig.value.max);
    var min_money = parseFloat(withdrawConfig.value.min_money);//最低兑换积分
    var max_money = parseFloat(withdrawConfig.value.max_money);//最高兑换积分

    // 判断是否能兑换
    var isForward = '';
    if (val < min_money || val > max_money) {
      isForward = false;
    } else {
      isForward = true;
    }
    that.setData({
      isForward: isForward
    })

    //计算输入手续费
    var fee = parseFloat(val) * percentage;
    if (percentage > 0) {
      if (fee < min) {
        fee = min;
      } else if (fee > max) {
        fee = max;
      }
      fee = parseFloat(fee).toFixed(2);
    }

    //根据余额计算手续费
    var b_fee = account_balance * percentage;//余额手续费
    if (percentage > 0) {
      if (b_fee < min) {
        b_fee = min;
      } else if (b_fee > max) {
        b_fee = max;
      }
    }
    b_fee = parseFloat(b_fee.toFixed(2));
    var b_max = account_balance;//最大兑换额度
    var is_all = false;
    if (b_max == parseFloat(val)) {
      is_all = true;
      fee = b_fee;
    }

    if (parseFloat(val) > b_max) {
      b_max = parseFloat(b_max).toFixed(2);
      // app.showToast('最大兑换额度为：' + b_max);
      that.setData({
        actualMoney: '',
        allMoney: '',
        msg: '最大兑换额度为：' + b_max,
        poundage: 0,
        money: 0,
        total: account_balance,
        isForward: false
      });
    } else {
      if (is_all) {
        var allMoney = b_max;
        var total = 0.00;
        val = account_balance;
      } else {
        var allMoney = val;
        var total = (account_balance - parseFloat(val)).toFixed(2);
      }
      var actualMoney = allMoney - fee;
      //转换格式
      fee = parseFloat(fee).toFixed(2);
      total = parseFloat(total).toFixed(2);
      actualMoney = parseFloat(actualMoney).toFixed(2);
      that.setData({
        allMoney: allMoney,
        total: total,
        poundage: fee,
        msg: '',
        actualMoney: actualMoney,
      });
    }
  },

  // 输入兑换积分
  getMoney(e) {
    var that = this;
    //账户余额
    var account_balance = parseFloat(workers_info.available_money);
    //输入金额
    var val = e.detail.value;
    //判断最后一位是否为小数点
    var check = val.substr(val.length - 1,1);
    //验证金额
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (!reg.test(val) && check != '.') {
      // account_balance = parseFloat(account_balance).toFixed(2);
      // app.showToast('请输入正确的兑换积分');
      that.setData({
        allMoney: '',
        msg: '请输入正确的兑换积分',
        poundage: 0,
        money: 0,
        total: account_balance
      });
      return;
    } else if ((val.split('.')).length - 1 > 1) {
      // account_balance = parseFloat(account_balance).toFixed(2);
      // app.showToast('请输入正确的兑换积分');
      that.setData({
        allMoney: '',
        msg: '请输入正确的兑换积分',
        poundage: 0,
        money: 0,
        total: account_balance
      });
      return;
    } else if ((val.indexOf('.')) == 0) {
      that.setData({
        allMoney: '',
        msg: '请输入正确的兑换积分',
        poundage: 0,
        money: 0,
        total: account_balance
      });
      return;
    }

    var percentage = that.data.accountType == 1 ? parseFloat(withdrawConfig.value.percentage) : parseFloat(withdrawConfig.value.wx_percentage);
    var min = parseFloat(withdrawConfig.value.min);
    var max = parseFloat(withdrawConfig.value.max);
    var min_money = parseFloat(withdrawConfig.value.min_money);//最低兑换积分
    var max_money = parseFloat(withdrawConfig.value.max_money);//最高兑换积分

    // 判断是否能兑换
    var isForward = '';
    if (val < min_money || val > max_money) {
      isForward = false;
    }else{
      isForward = true;
    }
    that.setData({
      isForward: isForward
    })

    //计算输入手续费
    var fee = parseFloat(val) * percentage;
    if (percentage > 0){
      if (fee < min) {
        fee = min;
      } else if (fee > max) {
        fee = max;
      }
      fee = parseFloat(fee).toFixed(2);
    }

    //根据余额计算手续费
    var b_fee = account_balance * percentage;//余额手续费
    if (percentage > 0) {
      if (b_fee < min) {
        b_fee = min;
      } else if (b_fee > max) {
        b_fee = max;
      }
    }
    b_fee = parseFloat(b_fee.toFixed(2));
    var b_max = account_balance;//最大兑换额度
    var is_all = false;
    if (b_max == parseFloat(val)) {
      is_all = true;
      fee = b_fee;
    }

    if (parseFloat(val) > b_max) {
      b_max = parseFloat(b_max).toFixed(2);
      // app.showToast('最大兑换额度为：' + b_max);
      that.setData({
        actualMoney: '',
        allMoney: '',
        msg: '最大兑换额度为：' + b_max,
        poundage: 0,
        money: 0,
        total: account_balance,
        isForward: false
      });
    } else {
      if (is_all) {
        var allMoney = b_max;
        var total = 0.00;
        val = account_balance;
      } else {
        var allMoney = val;
        var total = (account_balance - parseFloat(val)).toFixed(2);
      }
      var actualMoney = allMoney - fee;
      //转换格式
      fee = parseFloat(fee).toFixed(2);
      total = parseFloat(total).toFixed(2);
      actualMoney = parseFloat(actualMoney).toFixed(2);
      that.setData({
        allMoney: allMoney,
        total: total,
        money: val,
        poundage: fee,
        msg: '',
        actualMoney: actualMoney,
      });
    }
  },

  // 选择兑换账户
  choosecard: function() {
    this.setData({
      prohibit: true
    })
  },

  // 关闭弹窗
  closemodel: function() {
    this.setData({
      prohibit: false
    })
  },

  // 选择银行卡
  cardItem: function(e) {
    var bank_id = e.currentTarget.dataset.id;
    this.setData({
      prohibit: false,
      isChoose: false,
      index: e.currentTarget.dataset.index,
      bank_id: bank_id,
      accountType: 1, //账户类型
    });
    if (this.data.money != '') {
      this.checkMoney();
    }
  },

  // 选择微信
  wxItem() {
    this.setData({
      prohibit: false,
      isChoose: false,
      accountType: 2, //账户类型
    });
    if (this.data.money != '') {
      this.checkMoney();
    }
  },

  //全部兑换
  all(e) {
    var that = this;
    //计算手续费
    var money = parseFloat(workers_info.available_money);
    var percentage = that.data.accountType == 1 ? parseFloat(withdrawConfig.value.percentage) : parseFloat(withdrawConfig.value.wx_percentage);
    var fee = money * percentage;
    fee = parseFloat(fee).toFixed(2);
    var min = parseFloat(withdrawConfig.value.min);
    var max = parseFloat(withdrawConfig.value.max);
    if (percentage > 0){
      if (fee < min) {
        fee = min;
      } else if (fee > max) {
        fee = max;
      }
    }

    var tmp = money;
    var min_money = parseFloat(withdrawConfig.value.min_money);
    if (tmp < min_money) {
      app.showToast('最低兑换积分' + min_money);
      return false;
    }
    var max_money = parseFloat(withdrawConfig.value.max_money);
    if (tmp > max_money) {
      app.showToast('最高兑换积分' + max_money);
      return false;
    }
    var actualMoney = tmp - fee;
    tmp = parseFloat(tmp).toFixed(2);
    var total = parseFloat(0).toFixed(2);
    actualMoney = parseFloat(actualMoney).toFixed(2);
    // 判断是否能兑换
    var isForward = '';
    if (tmp < min_money || tmp > max_money) {
      isForward = false;
    } else {
      isForward = true;
    }
    that.setData({
      allMoney: tmp,
      total: total,
      poundage: fee,
      money: workers_info.available_money,
      actualMoney: actualMoney,
      isForward: isForward
    })
  },

  //添加银行卡
  navAddCard() {
    wx.navigateTo({
      url: '/pages/user/addeditAccount/addeditAccount?type=2&role=' + this.data.role,
    })
  },
  // 授权手机号码
  bindPhone(e) {
    if (!this.data.isForward) {
      return false;
    }
    console.log('e', e);
    let is_phone = e.detail.iv ? true : false;
    let auth_detail = e.detail;
    if (is_phone) {
      this.decodePhone(auth_detail);
    }
    if (!is_phone) app.showToast('请授权手机号码，才能兑换哦~');
  },
  //解码手机号
  decodePhone(auth_detail) {
    console.log('auth_detail', auth_detail);
    app.ajax({
      url: 'Common/Wx/aesPhoneDecrypt',
      data: {
        openid: wx.getStorageSync('openid'),
        data: auth_detail.encryptedData,
        iv: auth_detail.iv,
      },
      success: (res) => {
        console.log('res>>>>>>>>', res);
        if (res.data.code == 1000) {
          this.setData({
            auth_phone: res.data.data.phoneNumber,
            is_phone: true,
            codeShow: true
          });
          this.sendSms();
        } else {
          this.setData({
            auth_phone: '',
            is_phone: false
          });
          app.showToast(res.data.message);
        }
      }
    });
  },
  // 发送验证码
  sendSms() {
    var that = this;
    if (isSend) return;
    isSend = true;
    app.ajax({
      url: 'Common/Common/sendSms',
      data: { tel: that.data.auth_phone, },
      success: function (res) {
        that.setData({
          sms_txt: res.data.message
        })
        if (res.data.code == 1000) {
          that.setData({
            codeShow: true,
            times: 60
          });
          clearInterval(timer);
          timer = setInterval(() => {
            let times = that.data.times;
            if (times <= 0) {
              clearInterval(timer);
              that.setData({
                times: 0
              });
            } else {
              that.setData({
                times: times - 1
              });
            }
          }, 1000);
        } else {
          app.showToast(res.data.message);
        }
        isSend = false;
      }
    });
  },
  // 数据验证码
  bindCode(e) {
    var that = this;
    var inputIndex = that.data.inputIndex;
    var value = e.detail.value;
    var inputArr = value.split('');
    console.log('inputArr', inputArr);
    var length = inputArr.length;
    that.setData({
      inputValue: value,
      inputArr: inputArr
    });
    console.log('length', length);
    console.log('inputIndex', inputIndex);
    if (length < 6) {
      that.setData({
        inputIndex: length
      });
    } else {
      that.startCash(value); // 开始兑换
    }
  },
  // 关闭手机验证码弹窗
  closeCode() {
    var that = this;
    clearInterval(timer);
    that.setData({
      codeShow: false,
      inputValue: '',
      inputIndex: 0,
      inputArr: []
    });
  },
  // 兑换
  newExtract() {
    var that = this;
    if (!that.data.isForward) {
      return false;
    }
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (!reg.test(that.data.money)) {
      app.showToast('请输入正确的兑换积分');
      return false;
    }
    var money = Math.floor(parseFloat(that.data.money * 1000)) / 1000;
    var min_money = Math.floor(parseFloat(withdrawConfig.value.min_money * 1000)) / 1000;
    var max_money = Math.floor(parseFloat(withdrawConfig.value.max_money * 1000)) / 1000;
    if (money < min_money) {
      app.showToast('最低兑换积分' + withdrawConfig.value.min_money);
      return false;
    }
    if (money > max_money) {
      app.showToast('最高兑换积分' + withdrawConfig.value.max_money);
      return false;
    }
    this.setData({
      auth_phone: that.data.accountType==1?that.data.index.bank_phone:that.data.auth_phone,
      codeShow: true
    });
    this.sendSms();
  },
  // 开始兑换
  startCash(sms_code) {
    var that = this;
    if (!that.data.isForward) {
      return false;
    }
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (!reg.test(that.data.money)) {
      app.showToast('请输入正确的兑换积分');
      return false;
    }
    var money = Math.floor(parseFloat(that.data.money * 1000)) / 1000;
    var min_money = Math.floor(parseFloat(withdrawConfig.value.min_money * 1000)) / 1000;
    var max_money = Math.floor(parseFloat(withdrawConfig.value.max_money * 1000)) / 1000;
    if (money < min_money) {
      app.showToast('最低兑换积分' + withdrawConfig.value.min_money);
      return false;
    }
    if (money > max_money) {
      app.showToast('最高兑换积分' + withdrawConfig.value.max_money);
      return false;
    }
    if (isRepeat) {
      return;
    }
    isRepeat = true;

    var openid = wx.getStorageSync('openid');
    app.ajax({
      url: "User/Withdraw/withdrawDepositApply",
      data: {
        role: that.data.role,
        account: that.data.accountType == 1 ? that.data.bank_id : openid,
        account_type: that.data.accountType,
        money: that.data.money,
        sms_code: sms_code,
        phone: that.data.auth_phone
      },
      success: function (res) {
        isRepeat = false;
        if (res.data.code == 1000) {
          // 关闭发送验证码弹窗
          that.setData({
            codeShow: false
          });
          app.showToast(res.data.message)
          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        } else {
          app.showToast(res.data.message)
        }
      }
    })

  },


  // 获取兑换信息
  withdrawDepositInfo() {
    var that = this;
    app.ajax({
      url: "User/Withdraw/withdrawDepositInfo",
      data: {
        role: that.data.role
      },
      success: function(res) {
        if (res.data.code == 1000) {
          var accountType = '';
          var chooseItem = '';
          var bankId = '';
          var isChoose = true;
          // 如果有银行卡兑换权限，默认选中第一张的银行卡
          if (res.data.data.withdraw_config.support_bank && res.data.data.banks.length > 0) {
            bankId = res.data.data.banks[0].bank_id;
            accountType = 1;
            chooseItem = res.data.data.banks[0];
            isChoose = false;
          } else if (res.data.data.withdraw_config.support_weixin) {
            accountType = 2;
            isChoose = false;
          }
          that.setData({
            banks: res.data.data.banks,
            total: res.data.data.workers_info.available_money,
            withdraw_config: res.data.data.withdraw_config,
            index: chooseItem,
            bank_id: bankId,
            accountType,
            isChoose
          })
          workers_info = res.data.data.workers_info;
        } else {
          app.showToast(res.data.message)
        }
      }
    })
  },
  // 获取兑换配置
  withdrawConfig() {
    var that = this;
    app.ajax({
      url: "Common/Common/getBalanceConfig",
      data: {
        key: 'payment_fee'
      },
      success: function (res) {
        var result = res.data.data;
        if (result != null) {
            withdrawConfig= result;
        } else {
          app.showToast('兑换功能已关闭')
          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        }
      }
    })
  },
})
